package org.ym.file.domain.model.node.common.download;

import org.apache.commons.io.FileUtils;
import org.ym.tools.FileTool;
import org.ym.tools.StreamTool;

import java.io.InputStream;

/**
 * 一般上传方法
 * @author ym
 */
public class NormalUpload implements UploadInterface{
    private static NormalUpload instance;

    /**
     * 获取实例
     * @return
     */
    public static NormalUpload getInstance(){
        if(instance == null){
            synchronized (NormalUpload.class){
                if(instance == null){
                    instance = new NormalUpload();
                }
            }
        }
        return instance;
    }

    @Override
    public FileUploadResult upload(InputStream source, FileUploadCommand fileUploadCommand) {
        try(InputStream inputStream = source){
            long size = StreamTool.writeFile(inputStream, fileUploadCommand.getFilePath());
            return FileUploadResult.builder().size(size).filePath(fileUploadCommand.getFilePath()).build();
        }catch (Exception e){
            //报错删除文件,防止文件冗余产生
            FileTool.deleteFile(fileUploadCommand.getFilePath());
            throw new RuntimeException(e);
        }
    }

    @Override
    public FileUploadResult deal(FileUploadCommand fileUploadCommand) {
        return FileUploadResult.builder().filePath(fileUploadCommand.getFilePath()).size(FileUtils.sizeOf(fileUploadCommand.getFilePath().toFile())).build();
    }
}
